<?php

namespace young;

use young\StringCrypt;

class Common
{

//************格式验证*****************************

    /**
     * todo 判断是否是超链接
     * @param string $url
     * @return bool
     */
    public static function is_url($url)
    {
        return (bool)preg_match("/^http:\/\/|^https:\/\//", $url);
    }

    /**
     * todo 判断是否是手机号
     * @param string $phone_number
     * @return bool
     */
    public static function is_phone_number($phone_number)
    {
        return (bool)preg_match("/^1(3|4|5|7|8)[0-9]\\d{8}$/", $phone_number);
    }


//************数据处理*****************************

    /**
     * todo 手机号码中间部分用*替换
     * @param string $phone_number
     * @return string
     */
    public static function phone_number_encode($phone_number)
    {
        return substr($phone_number, 0, 3) . '****' . substr($phone_number, 7, 4);
    }

    /**
     * todo 字节格式化
     * @param int $size
     * @param int $dec
     * @return string
     */
    public static function byte_format($size, $dec = 2)
    {
        $a = array("B", "KB", "MB", "GB", "TB", "PB");
        $pos = 0;
        while ($size >= 1024) {
            $size /= 1024;
            $pos++;
        }
        return round($size, $dec) . " " . $a[$pos];
    }

    /**
     * todo 距离格式化
     * @param int $distance
     * @return string
     */
    public static function distance_format($distance = 0)
    {
        $distance = intval($distance);
        if ($distance == 0) {
            return '未知';
        } elseif ($distance >= 1000) {
            return round(($distance / 1000), 2) . 'km';
        } else {
            return $distance . 'm';
        }
    }

    /**
     * todo 时间格式化
     * @param int $timestamp
     * @return bool|string
     */
    public static function time_format($timestamp = 0)
    {
        $timestamp = intval($timestamp);
        $difference = time() - $timestamp;

        if ($timestamp === 0) {
            return '时间错误';
        } elseif ($difference < 60) {
            return $difference . '秒前';
        } elseif ($difference < 3600) {
            return intval($difference / 60) . '分钟前';
        } elseif ($difference < 86400) {
            return intval($difference / 60 / 60) . '小时前';
        } else {
            return date('Y-m-d H:i:s', $timestamp);
        }
    }

    /**
     * todo 表单文本域保存数据转换
     * @param $text
     * @param string $s
     * @return string
     */
    public static function text_area_encode($text, $s = ',')
    {
        $array = explode($s, str_replace(["\r", "\n"], ['', $s], $text));
        foreach ($array as $index => $item) {
            $array[$index] = trim($item);
        }
        return implode($s, array_filter($array));
    }

    /**
     * todo 表单文本域读取数据转换
     * @param $text
     * @param string $s
     * @return string
     */
    public static function text_area_decode($text, $s = ',')
    {
        return (string)str_replace($s, "\r\n", $text);
    }

    /**
     * todo 二维数组排序
     * @param array $array
     * @param string $field
     * @param int $rule
     * @return array
     */
    public static function array_sort($array = [], $field = '', $rule = SORT_ASC)
    {
        $sort = array();
        foreach ($array as $value) {
            $sort[] = $value[$field];
        }
        array_multisort($sort, $rule, $array);
        return $array;
    }

//************加密处理*****************************

    /**
     * todo 字符串加密
     * @param string $text
     * @param string $key
     * @return string
     */
    public static function string_encode($text, $key = '123456')
    {
        $text = str_replace(['/', '.', '#', ':', '&', '?', '+'], ['[a]', '[b]', '[c]', '[d]', '[e]', '[f]', '[g]'], $text);
        return urlencode(StringCrypt::encrypt($text, $key));
    }

    /**
     * todo 字符串解密
     * @param $text
     * @param string $key
     * @return string
     */
    public static function string_decode($text, $key = '123456')
    {
        $text = StringCrypt::decrypt($text, $key);
        return (string)str_replace(['[a]', '[b]', '[c]', '[d]', '[e]', '[f]', '[g]'], ['/', '.', '#', ':', '&', '?', '+'], $text);
    }

//************HTTP请求*****************************

    /**
     * todo 发起POST请求
     * @param string $url
     * @param array $request_data
     * @param int $content_type
     * @return mixed
     */
    public static function request_post($url = '', $request_data = [], $content_type = 1)
    {
        $request_data = ($content_type == 1) ? http_build_query($request_data) : $request_data;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request_data);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    /**
     * todo 发起GET请求
     * @param string $url
     * @return mixed
     */
    public static function request_get($url = '')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    /**
     * todo 生成固定长度随机字符串
     * @param int $length
     * @return string
     */
    public static function rand_string($length = 5)
    {
        $array = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
        shuffle($array);
        $value = '';
        for ($i = 0; $i < $length; $i++) {
            $value .= $array[array_rand($array, 1)];
        }
        return $value;
    }

    /**
     * todo 数组转XML
     * @param $array
     * @return string
     */
    public static function arrayToXml($array)
    {
        $xml = "<xml>";
        foreach ($array as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    /**
     * todo XML转数组
     * @param $xml
     * @return mixed
     */
    public static function xmlToArray($xml)
    {
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }

    public static function getCityNameByIp($ip)
    {
        if ($ip) {
            $result = self::request_get('http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip);
            $result = json_decode($result, true);
            if ($result['code'] == 0 && $result['data']['city']) {
                return $result['data']['city'];
            }
        }
        return '';
    }

    /**
     * todo 抛出错误信息
     * @param $msg
     * @throws \Exception
     */
    public static function throw_error($msg = '⊙﹏⊙‖∣°')
    {
        throw new \Exception($msg);
    }

    /**
     * todo 结束运行
     * over
     */
    public static function over()
    {
        exit('⊙﹏⊙‖∣°');
    }
}